package com.chagee.store.operation.server.service.biz;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chagee.base.utils.PaginationData;
import com.chagee.base.utils.PaginationRequest;
import com.chagee.store.operation.api.enums.AppealStatusEnum;
import com.chagee.store.operation.api.enums.StoreTaskEnum;
import com.chagee.store.operation.api.response.vo.FileVO;
import com.chagee.store.operation.common.constant.CommonConstant;
import com.chagee.store.operation.server.entity.TaskExecutionDO;
import com.chagee.store.operation.server.entity.WorkOrderDO;
import com.chagee.store.operation.server.event.dao.TaskExecutionMapper;
import com.chagee.store.operation.server.event.service.TaskExecutionBaseService;
import com.chagee.store.operation.server.event.service.WorkOrderBaseService;
import com.chagee.store.operation.server.model.param.ApprovalAppealParam;
import com.chagee.store.operation.server.model.param.TaskExecutionAppealRequest;
import com.chagee.store.operation.api.request.TaskExecutionRequest;
import com.chagee.store.operation.server.model.param.ViewReasonsParam;
import com.chagee.store.operation.api.response.vo.AiResultVO;
import com.chagee.store.operation.api.bo.AppealExtraVO;
import com.chagee.store.operation.server.model.vo.ApprovalAppealReasonResponse;
import com.chagee.store.operation.api.response.TaskExecutionResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName TaskExecutionBizService  //类名称
 * @Description: //类描述
 * @Author: Jacky-zhan	//作者
 * @CreateDate: 2024/7/2 17:53	//创建时间
 * @UpdateUser: Jacky-zhan  //变更者
 * @UpdateDate: 2024/7/2 17:53	//更新时间
 * @UpdateRemark: //更新的信息
 * @Version: 1.0    //版本号
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TaskExecutionBizService extends ServiceImpl<TaskExecutionMapper, TaskExecutionDO> {

	@Autowired
	private TaskExecutionBaseService taskExecutionBaseService;
	@Resource
	private WorkOrderBaseService workOrderBaseService;

	public void updateBatch(List<TaskExecutionDO> executionDOList) {
		if (CollectionUtils.isNotEmpty(executionDOList)) {
			executionDOList.forEach(taskExecutionDO -> {
				this.update(taskExecutionDO);
			});
		}
	}

	public void update(TaskExecutionDO taskExecutionDO) {
		taskExecutionBaseService.update(
			lambdaUpdate().eq(TaskExecutionDO::getId, taskExecutionDO.getId())
				.set(TaskExecutionDO::getEarlyAcceptance, taskExecutionDO.getEarlyAcceptance())
				.set(TaskExecutionDO::getReliableTime, taskExecutionDO.getReliableTime()).getWrapper());
	}


	//工单关联任务查询
	public PaginationData<TaskExecutionResponse> query(PaginationRequest<TaskExecutionRequest> request) {
		LambdaQueryWrapper<TaskExecutionDO> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(TaskExecutionDO::getWorkOrderNumber, request.getQueryParameter().getWorkOrderNumber());
		List<TaskExecutionDO> list = taskExecutionBaseService.list(wrapper);

		PaginationData<TaskExecutionResponse> result = new PaginationData<>();

		List<TaskExecutionResponse> dataList = new LinkedList<>();
		for (TaskExecutionDO taskExecutionDO : list) {
			TaskExecutionResponse response = new TaskExecutionResponse();
			BeanUtils.copyProperties(taskExecutionDO, response);
			response.setSchematicDrawing(JSON.parseArray(taskExecutionDO.getSchematicDrawing(), FileVO.class));
			response.setTakePictures(JSON.parseArray(taskExecutionDO.getTakePictures(), AiResultVO.class));
			response.setRemarkPicture(JSON.parseArray(taskExecutionDO.getRemarkPicture(), FileVO.class));
			if (taskExecutionDO.getClosingInspection() != null) {
				response.setClosingInspectionValue(taskExecutionDO.getClosingInspection() == 0 ? "已完成" : "无此项");
			}
			if (StringUtils.isNotBlank(taskExecutionDO.getEarlyAcceptance())) {
				response.setEarlyAcceptanceValue(Objects.requireNonNull(StoreTaskEnum.queryByType(taskExecutionDO.getEarlyAcceptance())).getDesc());
			}
			if (Objects.nonNull(taskExecutionDO.getAppealStatus())) {
				response.setAppealStatusValue(Objects.requireNonNull(AppealStatusEnum.getByType(taskExecutionDO.getAppealStatus())).getDesc());
			}
			if (StringUtils.equals(taskExecutionDO.getEarlyAcceptance(),StoreTaskEnum.NO.getType())) {
				response.setSortNum(NumberUtils.INTEGER_ONE);
			} else {
				response.setSortNum(NumberUtils.INTEGER_ZERO);
			}
			if (StringUtils.isNotBlank(taskExecutionDO.getExtra())) {
				AppealExtraVO appealExtraVO = JSON.parseObject(taskExecutionDO.getExtra(), AppealExtraVO.class);
				response.setExtraVO(appealExtraVO);
			}
			dataList.add(response);
		}
		dataList = dataList.stream().sorted(Comparator.comparing(TaskExecutionResponse::getSortNum, Comparator.reverseOrder())).collect(Collectors.toList());
		result.setPageList(dataList);
		return result;
	}

	public void checkScore(List<TaskExecutionDO> taskExecutionDOS, WorkOrderDO workOrderDO) {
		String documentScore = CommonConstant.ZERO;
		if (CollectionUtils.isNotEmpty(taskExecutionDOS)) {
			List<TaskExecutionDO> yesOrders = taskExecutionDOS.stream().filter(s -> StringUtils.equals(StoreTaskEnum.YES.getType(), s.getEarlyAcceptance())
				|| StringUtils.equals(StoreTaskEnum.SYSTEM_SATISFIED.getType(), s.getEarlyAcceptance())).collect(Collectors.toList());
			List<TaskExecutionDO> emptyOrders = taskExecutionDOS.stream().filter(s -> StringUtils.equals(StoreTaskEnum.EMPTY.getType(), s.getEarlyAcceptance())).collect(Collectors.toList());
			if (!CollectionUtils.isEmpty(yesOrders)) {
				// 工单评分  满意数量 / (总数量- 验收无此项) * 100
				BigDecimal score = new BigDecimal(yesOrders.size() * 100).divide(new BigDecimal(taskExecutionDOS.size() - emptyOrders.size()), NumberUtils.INTEGER_ZERO, BigDecimal.ROUND_HALF_UP);
				documentScore = score.toString();
			}
			if (StringUtils.isNotBlank(workOrderDO.getDocumentScore()) && !workOrderDO.getDocumentScore().equals(documentScore)){
				workOrderDO.setDocumentScore(documentScore);
				workOrderBaseService.updateById(workOrderDO);
			}
		}
	}

	/**
	 * 查询工单下的任务信息（任务的申诉状态不为空的）
	 *
	 * @param request 工单编号
	 * @return 任务信息（任务的申诉状态不为空的）
	 */
	public List<TaskExecutionResponse> queryTaskExecutionList(TaskExecutionAppealRequest request) {
		return taskExecutionBaseService.queryTaskExecutionList(request.getWorkOrderNumber(), request.getStoreNo());
	}

	/**
	 * PC端开早打样工单-申诉信息：审批申诉（通过/驳回）
	 *
	 * @param approvalAppealParam 审批入参
	 * @return true/false
	 */
	public Boolean approvalAppeals(ApprovalAppealParam approvalAppealParam) {
		return taskExecutionBaseService.approvalAppeals(approvalAppealParam);
	}

	/**
	 * PC端开早打样工单-申诉信息：查看驳回的原因/申诉原因
	 *
	 * @param viewReasonsParam 审批入参
	 * @return 申诉（驳回）原因证明
	 */
	public ApprovalAppealReasonResponse viewReasons(ViewReasonsParam viewReasonsParam) {
		return taskExecutionBaseService.viewReasons(viewReasonsParam);
	}
}
